#coding=UTF-8
#author：zhujingyuan

import requests,urllib3
from Params.TokenParas import HeadersWithUserToken
from Config.config import environmentData
from Log.logg import MyLog
from urllib3.exceptions import InsecureRequestWarning

urllib3.disable_warnings(InsecureRequestWarning)
my_logger=MyLog()

class SendRequests():

    def __init__(self,url,method,headers,type=0):
        self.method=method
        self.url=environmentData['VipClubAddress']+url
        self.headers=headers
        self.data={}
        self.type=type
        self.rsp=None
        self.url_log=url
        self.verity=False

    def set_data(self,dic):
        if isinstance(dic,dict):
            self.data=dic
        else:
            raise Exception(my_logger.error("{}please set the ParaType with dict".format(self.url_log)))

    def sendRequests(self):
        my_logger.info("start test {}".format(self.url))
        if self.method=='GET':
            if self.type==0:    #不带data参数的请求
                self.rsp=requests.get(url=self.url,headers=self.headers,verify=False)
                requests
            elif self.type==1: #带data参数的请求
                self.rsp=requests.get(url=self.url,headers=self.headers,params=self.data,verify=False)
            elif self.type==2: #带json参数的请求，这种api不多，偶遇一两个
                self.rsp=requests.get(url=self.url,headers=self.headers,json=self.data,verify=False)
            else:
                raise Exception(my_logger.error('{} request Get paraType is not supported'.format(self.url_log)))
        elif self.method=='POST':
            if self.type == 0:  # 不带data参数的请求
                self.rsp = requests.post(url=self.url, headers=self.headers,verify=False)
            elif self.type == 1:  # 带data参数的请求
                self.rsp = requests.post(url=self.url, headers=self.headers, data=self.data,verify=False)
            elif self.type == 2:  # 带json参数的请求
                self.rsp = requests.post(url=self.url, headers=self.headers, json=self.data,verify=False)
            else:
                raise Exception(my_logger.error('{}request POST paraType is not supported'.format(self.url_log)))
        elif self.method == 'DELETE':
            self.rsp = requests.delete(url=self.url, headers=self.headers, json=self.data,verify=False)
        elif self.method == 'PUT':
            self.rsp = requests.put(url=self.url, headers=self.headers, json=self.data,verify=False)
        else:
            # raise Exception('request method is not supported')
            raise Exception(my_logger.error("{} request method is not supported".format(self.url_log)))

        my_logger.info("the request data is {}".format(self.data))
        my_logger.info("the response data is {}".format(self.rsp.json()))

    #判断返回的状态码是否为200
    def rsp_status_code(self,excepted):
        if self.rsp is not None:
            assert self.rsp.status_code==excepted,my_logger.error("======test failed======: {} status_code return {}".format(self.url_log,self.rsp.status_code))
            my_logger.info("test pass：status_code rerurn 200")
        else:
            raise Exception(my_logger.error('{} the http response is none'.format(self.url_log)))

     # 断言返回值是否与预期一致
    def rsp_data(self, actual, excepted):
        assert actual == excepted, my_logger.error(
            '======test failed======：{} actual is not equal excepted!'.format(self.url_log))
        my_logger.info("test pass：Response value check successfully")

    # 断言期望值是否包含在返回值中
    def rsp_containsData(self, excepted):
        if excepted in self.rsp.text:
            assert True
            my_logger.info("test pass：Response value check successfully")
        else:
            assert False, my_logger.error(
                "======test failed======：{} Response value not contains {}.\n And the actual result is: {}".format(
                    self.url_log, excepted, self.rsp.text))
            # my_logger.info("The actual result is: {}".format(self.rsp.text))

    # 断言返回的数量是否与预期一致
    def rsp_data_count(self, excepted):
        assert len(self.rsp.json()) == excepted, my_logger.error(
            '======test failed======：{} the data counts is wrong!'.format(self.url_log))
        my_logger.info("test pass：the data counts is right")

    # 断言相应时间是否小于excepted,自定义返回时间
    def rsp_time(self, excepted):
        assert self.rsp.elapsed.total_seconds() * 1000 < excepted, my_logger.error(
            '======test failed======：{} Response time exceeds expected!'.format(self.url_log))
        my_logger.info("test pass：Response time less than or equal to expected")


class SendRequestsWithAssert():
    # Post接口比较多，默认method为POST，type为2
    def __init__(self, url, method='POST', headers=HeadersWithUserToken, data=None, type=2, exp_status_code=200,
                 exp_time=20000, exp_value=None, exp_count=None):
        self.method = method  # 请求方法
        self.url = url  # 请求url
        self.headers = headers  # 请求头
        self.data = data  # 请求数据
        self.type = type  # 请求类型
        self.rsp = None  # 请求结果
        self.url_log = url  # 输出日志中用到
        self.rsp_status_code = exp_status_code  # Http响应状态码
        self.exp_time = exp_time  # 预期响应时间
        self.exp_value = exp_value  # 预期响应值
        self.exp_count = exp_count  # 预期响应数量

    def sendRequestsWithAssert(self):
        request = SendRequests(self.url, self.method, self.headers, self.type)
        if self.type != 0:
            request.set_data(self.data)  # type=0时不赋值data
        request.sendRequests()
        self.rsp = request.rsp.json()  # 获取响应内容

        request.rsp_status_code(self.rsp_status_code)  # 断言状态码
        request.rsp_time(self.exp_time)  # 断言响应时间
        if self.exp_value is not None:
            request.rsp_containsData(self.exp_value)  # 断言响应值中是否包含期望值
        if self.exp_count is not None:
            request.rsp_data_count(self.exp_count)  # 断言返回的数量是否与预期一致


















































